﻿using System.Collections.Generic;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using WorkLogger.Client.DataAccess.Mappings;

namespace WorkLogger.Client.DataAccess {
	public static class NHibernateHelper {
		private static ISessionFactory sessionFactory;
		private static Configuration configuration;
		private static HbmMapping mapping;

		public static ISession OpenSession() {
			//Open and return the nhibernate session
			return SessionFactory.OpenSession();
		}

		public static ISessionFactory SessionFactory {
			get { return sessionFactory ?? (sessionFactory = Configuration.BuildSessionFactory()); }
		}

		public static Configuration Configuration {
			get { return configuration ?? (configuration = CreateConfiguration()); }
		}

		public static HbmMapping Mapping {
			get { return mapping ?? (mapping = CreateMapping()); }
		}

		public static string DatabasePath { get; set; }

		private static Configuration CreateConfiguration() {
			var newConfiguration = new Configuration();
			//Loads properties from hibernate.cfg.xml
			newConfiguration.Configure();

			string connectionString = string.Format("Data Source=\"{0}\";Version=3;New=True", DatabasePath);
			newConfiguration.SetProperty("connection.connection_string", connectionString);
			//Loads nhibernate mappings 
			newConfiguration.AddDeserializedMapping(Mapping, null);

			return newConfiguration;
		}

		private static HbmMapping CreateMapping() {
			var mapper = new ModelMapper();
			//Add the person mapping to the model mapper
			mapper.AddMappings(new List<System.Type> { typeof(WorkDayMap), typeof(LunchTimeMap) });
			//Create and return a HbmMapping of the model mapping in code
			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
	}
}